<?php

namespace Topxia\WebBundle\Controller;

use Topxia\Common\ArrayToolkit;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Topxia\System;

class DownloadController extends BaseController
{

    public function indexAction (Request $request)
    {
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if(strpos($user_agent,'MicroMessenger')===false){
		}else{
			return $this->render('TopxiaWebBundle:Download:wx.html.twig');
		}
		$filename = $request->query->get('s');
		if(strstr($filename,'../')){
			$arr = array('status'=>'error', 'message'=>"403 路径中不能包含‘../’字样");
			return $this->render('TopxiaWebBundle:Download:index.html.twig', $arr);
		}
		
		if(!file_exists($filename)){
			$arr = array('status'=>'error', 'message'=>"404 找不到文件");
			return $this->render('TopxiaWebBundle:Download:index.html.twig', $arr);
		}
		
		$info = pathinfo($filename);
		if (in_array($info['extension'],array('php','yml','config','htaccess','bak','xml','wsdl'))){
			$arr = array('status'=>'error', 'message'=>"403 不允许下载以“.{$info['extension']}”为后缀的文件");
			return $this->render('TopxiaWebBundle:Download:index.html.twig', $arr);
		}
		return $this->createJsonResponse($this->downfile($filename));
    }
	
	private function downfile($fileurl)
	{
		$filename=$fileurl;
		
		
		$file  =  fopen($filename, "rb");
		Header( "Content-type:  application/octet-stream ");
		Header( "Accept-Ranges:  bytes ");
		Header('Content-Length: ' . filesize($filename));
		Header( "Content-Disposition:  attachment;  filename= ".$filename);
		$contents = "";
		while (!feof($file)) {
			$contents .= fread($file, 8192);
		}
		fclose($file); 
		echo $contents;
	}
}